<template>
  <div class="page-main" v-title data-title="工程采购申请列表">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>工程采购申请列表</span></div>
    <div class="container">
      <div class="header">
        <a-row type="flex" justify="space-between" align="middle">
          <a-col style="display: flex; justify-content: start">
            <a-button type="primary" class="hte-btn del-btn" @click="jumpToTcPurchase">创建采购申请</a-button>
            <a-button class="hte-btn del-btn" @click="handleSearch">刷新</a-button>
            <a-button class="hte-btn del-btn" @click="toHipByPlanOpen">打开采购计划</a-button>
            <!--
              <a-button type="primary" class="hte-btn del-btn" @click="addApplyConsum">创建</a-button>
              <a-button class="hte-btn del-btn" v-if="searchPlatForm == '1'" @click="editApplyConsum">编辑</a-button>
              <a-button class="hte-btn del-btn" v-if="searchPlatForm == '1'" @click="removeApplyConsum"
              style="color: red">删除</a-button> 
              <a-button class="hte-btn del-btn" v-if="searchPlatForm == '1'" @click="exportExcle" style="color: red">导出</a-button> 
            -->
            <!--<a-button class="hte-btn del-btn" @click="toHipOpen">在HIP查看</a-button>-->
            
            <!-- 
              <a-radio-group default-value="1" button-style="solid" v-model="searchPlatForm" @change="handleSearch"
                style="margin-left: 8px">
                <a-radio-button value="1"> 海芯 </a-radio-button>
                <a-radio-button value="2"> HIP </a-radio-button>
              </a-radio-group>
            -->
          </a-col>
          <a-col style="display: flex; justify-content: end">
            <a-button class="hte-btn del-btn" @click="showSearchForm = true">高级搜索</a-button>
          </a-col>
        </a-row>
      </div>

      <a-modal :visible="showSearchForm" width="70vw" :bodyStyle="{ padding: '10px' }" title="高级查询" @ok="handleSearch"
        @cancel="showSearchForm = false">
        <a-form-model ref="ruleForm" :laba-col="labelCol" :wrapper-col="wrapperCol"
          @keyup.enter.native="handleToSearch">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item label="状态:">
                <a-select allowClear v-model="searchForm.status" placeholder="申领状态">
                  <a-select-option value=""> 全部 </a-select-option>
                  <template v-for="item in codeMaps.HtePurchaseApplyStatus">
                    <a-select-option :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </template>
                </a-select>
              </a-form-model-item>
            </a-col>
            
            <a-col :span="8">
              <a-form-model-item label="采购申请号:">
                <a-input v-model="searchForm.applyNo" allowClear> </a-input>
              </a-form-model-item>
            </a-col> 
            <a-col :span="8">
              <a-form-model-item label="采购项名称:">
                <a-input v-model="searchForm.itemName" allowClear> </a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item label="项目编号:">
                <a-input v-model="searchForm.projectCode" allowClear> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="项目经理:">
                <a-input v-model="searchForm.projectManager" allowClear> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="费用支出哈:">
                <a-input v-model="searchForm.costNumber" allowClear> </a-input>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-model-item label="申请人:">
                <a-input v-model="searchForm.createUser" allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
              <a-form-model-item label="HIP采购申请号:">
                <a-input v-model="searchForm.applyUser" allowClear />
              </a-form-model-item>
            </a-col>
            <a-col :span="8">
                <a-form-model-item label="HIP项目状态:">
                  <a-input v-model="searchForm.auditUser" allowClear />
                </a-form-model-item>
            </a-col>   
          </a-row>
        </a-form-model>
      </a-modal>
      <div class="content-list">
        <a-table :scroll="{ x: 1800 }" class="hte-table-content" :columns="columns" :data-source="records"
          :pagination="false" :rowKey="(record) => record.id"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" :customRow="customRow"
          bordered>
          <template slot="sortIndexRender" slot-scope="text, record, index">
            {{ index + 1 }}
          </template>

          <template slot="hipApplyNoRender" slot-scope="text, record, index">
              <span @click="editToTcPurchase(record.hipId)" class="font-active">
                {{ record.hipApplyNo }}
              </span>
          </template>

          <template slot="statusRender" slot-scope="text, record">
            <template v-for="(code, index) in codeMaps.HtePurchaseApplyStatus">
              <span :key="index" v-if="record.status == code.code"> {{ code.name }} </span>
            </template>
          </template>
          <template slot="applyNoRender" slot-scope="text, record">
            <span class="font-active" @click="toDetail(record.id)"> {{ record.applyNo }} </span>
          </template>
          <template slot="createTimeRender" slot-scope="text, record">
            {{ formatDate(record.createTime || '', 'yyyy-MM-dd HH:mm:ss') }}
          </template>
          <template slot="hipApplyStatusRender" slot-scope="text, record">
            <span v-if="searchPlatForm != '1'"> HIP采购单 </span>
            <template v-else v-for="(code, index) in codeMaps.HipPurchaseApplyStatus">
              <span :key="index" v-if="record.hipApplyStatus == code.code"> {{ code.name }} </span>
            </template>
          </template>
        </a-table>
        <a-pagination show-size-changer :default-current="1" :total="searchForm.total" @change="pageChange"
          @showSizeChange="onShowSizeChange" :show-total="(total) => `共 ${total} 条记录`" />
      </div>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { postAction, getAction } from '@/api/manage'
import { formatDate } from '@/utils/util'
export default {
  name: 'ApplyAddConsum',
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractTaskList',
      },
      urls: {
        page: '/htePurchaseApply/page',
        hipPage: '/htePurchaseApply/hipPage',
        delete: '/htePurchaseApply/delete',
        codes: '/manage/codeInfo/queryByTypes',
        getEncryptInfo:'/htePurchaseApply/getEncryptInfo'
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'sortIndex',
          scopedSlots: { customRender: 'sortIndexRender' },
          width: '80px',
          align: 'center',
        },
        // {
        //   title: '状态',
        //   dataIndex: 'status',
        //   scopedSlots: { customRender: 'statusRender' },
        //   width: '130px',
        //   align: 'center',
        // },
        // {
        //   title: '采购申请号',
        //   dataIndex: 'applyNo',
        //   scopedSlots: { customRender: 'applyNoRender' },
        //   width: '160px',
        //   align: 'center',
        // },
        {
          title: '采购申请号',
          dataIndex: 'hipApplyNo',
          width: '200px',
          align: 'center',
          scopedSlots: {customRender:'hipApplyNoRender'}
        },
        // {
        //   title: 'HIP项目状态',
        //   dataIndex: 'hipApplyStatys',
        //   width: '200px',
        //   align: 'center',
        //   scopedSlots: { customRender: 'hipApplyStatusRender' },
        // },
        {
          title: '采购项名称',
          dataIndex: 'itemName',
          width: '200px',
          align: 'center',
          customCell: () => {
            return {
              style: {
                width: '200px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.itemName}>
              {record.itemName}
            </a-tooltip>
          ),
        },
        {
          title: '项目编号',
          dataIndex: 'projectCode',
          width: '120px',
          align: 'center',
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '200px',
          align: 'center',
          customCell: () => {
            return {
              style: {
                width: '200px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.projectName}>
              {record.projectName}
            </a-tooltip>
          ),
        },
        {
          title: '项目经理',
          dataIndex: 'projectManager',
          width: '120px',
          align: 'center',
        },
        {
          title: '签订公司',
          dataIndex: 'signCompany',
          width: '200px',
          align: 'center',
          customCell: () => {
            return {
              style: {
                width: '200px',
                overflow: 'hidden',
                whiteSpace: 'nowrap',
                textOverflow: 'ellipsis',
                cursor: 'pointer',
              },
            }
          },
          customRender: (text, record) => (
            <a-tooltip placement="topLeft" title={record.signCompany}>
              {record.signCompany}
            </a-tooltip>
          ),
        },
        {
          title: '费用支出号',
          dataIndex: 'costNumber',
          width: '120px',
          align: 'left',
        },
        {
          title: '现场跟进人',
          dataIndex: 'followPerson',
          width: '110px',
          align: 'center',
        },
        {
          title: '预算金额(万元)',
          dataIndex: 'budgetAmount',
          width: '160px',
          align: 'center',
        },
        {
          title: '申请人',
          dataIndex: 'createUser',
          width: '120px',
          align: 'center',
        },
        {
          title: '申请时间',
          dataIndex: 'createTime',
          width: '200px',
          align: 'center',
          scopedSlots: { customRender: 'createTimeRender' },
        },
      ],
      showSearchForm: false,
      records: [],
      codeMaps: {},
      selectedRowKeys: [],
      selectedRow: [],
      loading: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      searchForm: {
        offset: 0,
        total: 0,
        page: 1,
        limit: 10,
        //current: 1,
        //pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
      },
      searchPlatForm: '2',
    }
  },

  created() {
    this.fetchCodes()
    this.fetchList()
  },
  methods: {
    formatDate,
    fetchList() {
      let url = this.urls.page
      if (this.searchPlatForm != '1') {
        url = this.urls.hipPage
      }
      console.log('this.searchForm:',this.searchForm)
      postAction(url, this.searchForm).then((res) => {
        if (res.code == 200) {
          this.records = res.result.records
          this.$set(this.searchForm, 'total', res.result.total)
          this.showSearchForm = false
          console.log('this.records:',JSON.stringify(this.records))
        } else {
          this.$message.error('获取数据失败')
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    fetchCodes() {
      getAction(this.urls.codes, { types: 'HtePurchaseApplyStatus,HipPurchaseApplyStatus' }).then((res) => {
        if (res.success) {
          this.codeMaps = res.result
        }
      })
    },
    handleDelete() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请先选择需要删除的行')
        return
      }
      this.$confirm('是否确认删除所选择行?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let ids = []
        for (let row of this.multipleSelection) {
          if (row.nid > 0) {
            ids.push(row.nid)
          }
        }
        if (ids.length > 0) {
          postAction(this.urls.deleteconsumItems, ids).then((res) => {
            if (res.code == 200) {
              this.$message.success('删除成功')
            } else {
              this.$message.error('删除失败')
            }
          })
        }
        let delCount = 0
        this.multipleSelection.forEach((row1) => {
          this.consum.items.splice(row1.rowIndex - delCount, 1)
          delCount++
        })
        this.countTotalPrice()
      })
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    customRow(record) {
      return {
        on: {
          dblclick: (event) => {
            this.toDetail(record.id)
          },
        },
      }
    },
    toDetail(id) {
      let urlJump = this.$router.resolve({ path: '/editPurchaseApply/' + id })
      window.open(urlJump.href, '_blank')
    },
    currentHandlerRenderFunc(record) {
      let text = ''
      if (record.handlerUser) {
        if (record.handlerTime) {
          text = record.handlerUser + '/' + record.handlerTime + '/' + record.stayDays + '天'
        }
      }
      return text
    },
    addApplyConsum() {
      let urlJump = this.$router.resolve({ path: '/addPurchaseApply' })
      window.open(urlJump.href, '_blank')
    },
    editApplyConsum() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        return this.$message.warning('请选择一条记录进行操作')
      } else {
        let urlJump = this.$router.resolve({ path: '/editPurchaseApply/' + this.selectedRowKeys[0] })
        window.open(urlJump.href, '_blank')
      }
    },
    removeApplyConsum() {
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        for (let row of this.selectedRow) {
          if (row.hipApplyNo) {
            return this.$message.warning('[' + row.applyNo + ']已同步到HIP，请勿删除')
          }
        }
      } else {
        return this.$message.warning('请至少选择一条记录进行操作')
      }
      let that = this
      this.$confirm({
        content: `确认删除已算中的记录吗？`,
        onOk: () => {
          getAction(that.urls.delete, { ids: that.selectedRowKeys.join(',') }).then((res) => {
            if (res.success) {
              that.$message.success('删除成功')
              this.handleSearch()
            }
          })
        },
      })
    },
    handleSearch() {
      this.$set(this.searchForm, 'current', 1)
      this.fetchList()
    },
    pageChange(current, pageSize) {
      // this.$set(this.searchForm, 'page', pageSize)
      // this.$set(this.searchForm, 'current', current)
      //this.$set(this.searchForm, 'pageNo', current)
      console.log('切页操作1:',current)
      console.log('切页操作2:',pageSize)

        this.$set(this.searchForm, 'page', current)
        this.$set(this.searchForm, 'limit', pageSize)

      this.fetchList()
    },
    onShowSizeChange(current, pageSize) {
      //this.$set(this.searchForm, 'pageSize', pageSize)
      //this.$set(this.searchForm, 'current', 1)
      this.$set(this.searchForm, 'page', 1)
      this.$set(this.searchForm, 'limit', pageSize)
      this.fetchList()
    },
    exportExcle() {
      let url = process.env.VUE_APP_API_BASE_URL + '/infrastructure/export?1=1'
      this.handleExportXls('采购申请单', url, this.searchForm)
    },
    toHipOpen() {
      if (!this.selectedRowKeys || this.selectedRowKeys.length != 1) {
        return this.$message.warning('请选择一条记录进行操作')
      } else {
        if (this.selectedRow[0].hipId) {
          this.openHip()
        } else {
          return this.$message.warning('所选记录未在HIP生成采购单')
        }
      }
    },
    toHipByPlanOpen() {
      this.openHipBuy()
    },
    openHip() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      window.open(
        process.env.VUE_APP_HIP_API_BASE_URL +
        '/common/mainTree.do?rturl=%2FHIP%2Fprojectapply%2FprojectInfoList.do%3FhteOpen%3Dtrue%26hipId%3D' +
        this.selectedRow[0].hipId +
        '&hteToken=' +
        token
      )
    },
    openHipBuy() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      window.open(
        process.env.VUE_APP_HIP_API_BASE_URL +
        '/main/index.do?rturl=%2FHIP%2FbuyPlan%2FmainPlanList.do%3Fleft_menu_id%3D40288090471a635301471a930c66002b' +
        '&hteToken=' +
        token
      )
    },
    jumpToTcPurchase(){
      console.log('跳转到天采采购申请')
      let url = this.urls.getEncryptInfo
      //let username = 'chenl'
      //console.log('url:',url)
      //console.log('username:',username)
      getAction(url).then((res) => {
            console.log(res)
            if(res.code == 200){
              let jumpTcUrl=res.result;
              console.log(jumpTcUrl)
              window.open(jumpTcUrl,'_blank')
            }else{
              this.$message.error('获取跳转信息失败')
            }   
      })
    },

    editToTcPurchase(hipId){
      console.log('编辑天采数据:',hipId)
      let url = this.urls.getEncryptInfo +'?id='+hipId
      getAction(url).then((res) => {
            console.log(res)
            if(res.code == 200){
              let jumpTcUrl=res.result;
              console.log(jumpTcUrl)
              window.open(jumpTcUrl,'_blank')
            }else{
              this.$message.error('获取跳转信息失败')
            }   
      })
    },

  },
}
</script>

<style scoped>
.demo-table-expand .a-form-model-item {
  margin-right: 0;
  margin-bottom: 0px;
}

.demo-table-expand span {
  display: inline-block;
  white-space: nowrap;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.a-form-model-item>>>.a-form-model-item--mini .a-form-model-item__label {
  color: #606266 !important;
  font-size: 12px !important;
  font-weight: normal;
}

.a-table>>>.a-table__expanded-cell[class*='cell'] {
  padding: 0px 0px 10px 0px;
}

.expand-title {
  height: 30px;
  line-height: 30px;
  background-color: #f1f1f1;
  padding-left: 50px;
  margin-bottom: 5px;
  font-size: 12px;
}

.a-form-model-item>>>.a-form-model-item__content {
  height: 36px;
}

.ellipse-tooltips {
  display: inline-block;
  white-space: nowrap;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ellipse-tooltips span {
  width: unset !important;
}

.a-range>>>.a-range-separator {
  width: 20px;
}

.searchForm {
  display: flex;
  flex-direction: row;
}

.searchForm-left {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  width: 85vw;
}

.searchForm-right {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  min-width: 280px;
  border-left: #cccccc 2px solid;
}
</style>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .banner {
    background-image: url(~@assets/contract-top.png);
  }

  .container {
    .content-list {
      margin-top: 15px;
    }
  }

  .font-active {
    cursor: pointer;
  }
}

/deep/ #process-container {
  width: unset !important;
}

#process-container {
  background: #fff;
  padding: 40px 22px;
  width: auto;
  margin: 0 auto;
  -webkit-box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
  box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.15);
}
</style>

